package com.ketangpai.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ketangpai.admin.dao.UserCourseDao;
import com.ketangpai.admin.entity.*;
import com.ketangpai.admin.entity.dto.*;
import com.ketangpai.admin.entity.param.CountParam;
import com.ketangpai.admin.entity.param.UserAddCourseParam;
import com.ketangpai.admin.entity.param.UserCourseParam;
import com.ketangpai.admin.mapper.CourseMapper;
import com.ketangpai.admin.mapper.UserCourseMapper;
import com.ketangpai.admin.mapper.UserMapper;
import com.ketangpai.admin.service.CourseService;
import com.ketangpai.admin.service.StuWorkService;
import com.ketangpai.admin.service.UserCourseService;
import com.ketangpai.admin.service.UserService;
import com.ketangpai.admin.utils.CourseCodeGenerator;
import com.ketangpai.admin.utils.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户与课程(UserCourse)表服务实现类d
 *
 * @author makejava
 * @since 2023-06-14 01:14:11
 */
@Service("userCourseService")

public class UserCourseServiceImpl implements UserCourseService {
    @Autowired
    private UserCourseMapper userCourseMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CourseMapper courseMapper;

    @Resource
    private UserCourseDao userCourseDao;
    @Resource
    private CourseService courseService;
    @Resource
    private UserService userService;
    @Resource
    private StuWorkService stuWorkService;

@Override
    public void getStuNum(){
        List<CountParam> userCount = userCourseMapper.getUserCount();
        for (CountParam countParam : userCount) {
            courseMapper.updateStuNum(countParam);
        }
    }
    private List<UserGetAllClassDTO> getDealClass(List<UserCourse> data) {
        List<CourseDTO> courseList = new ArrayList<>();
        List<UserGetAllClassDTO> userGetAllClassDTOS = new ArrayList<>();
        for (UserCourse datum : data) {
            CourseDTO courseDTO = courseMapper.selectByCourseId(datum.getCourseId());
            courseDTO.setName(userMapper.selectById(datum.getUserId()).getName());
            courseDTO.setIsTop(datum.getIsTop());
            courseDTO.setIsPigeonhole(datum.getIsPigeonhole());
            courseDTO.setType(datum.getType());
            courseDTO.setStudent_number(courseMapper.selectCountByCourseId(datum.getCourseId()));
            courseList.add(courseDTO);
        }
        Map<String, List<CourseDTO>> classifiedMap = new HashMap<>();
        for (CourseDTO courseDTO : courseList) {
            String studySemester = courseDTO.getAcademicYear() + " " + courseDTO.getSemester();
            // 如果该 id 还没有对应的列表，则创建一个新列表
            classifiedMap.computeIfAbsent(studySemester, k -> new ArrayList<>()).add(courseDTO);
        }
        // 输出分类结果
        for (Map.Entry<String, List<CourseDTO>> entry : classifiedMap.entrySet()) {
            String studySemester = entry.getKey();
            List<CourseDTO> courseDTOList = entry.getValue();
            userGetAllClassDTOS.add(new UserGetAllClassDTO(studySemester, courseDTOList));
        }

        return userGetAllClassDTOS;
    }
    private List<UserGetAllClassDTO> getDivideClass(UserCourseParam userCourseParam, List<UserCourse> data) {
        List<CourseDTO> courseList = new ArrayList<>();
        List<UserGetAllClassDTO> userGetAllClassDTOS = new ArrayList<>();
        for (UserCourse datum : data) {
            userCourseParam.setCourseId(datum.getCourseId());
            CourseDTO courseDTO = null;
            if (courseMapper.searchClass(userCourseParam)!=null) {
                courseDTO = courseMapper.searchClass(userCourseParam);
                courseDTO.setName(userMapper.selectById(datum.getUserId()).getName());
                courseDTO.setIsTop(datum.getIsTop());
                courseDTO.setIsPigeonhole(datum.getIsPigeonhole());
                courseDTO.setType(datum.getType());
                courseList.add(courseDTO);
            }
        }
        Map<String, List<CourseDTO>> classifiedMap = new HashMap<>();
        for (CourseDTO courseDTO : courseList) {
            String studySemester = courseDTO.getAcademicYear() + " " + courseDTO.getSemester();
            // 如果该 id 还没有对应的列表，则创建一个新列表
            classifiedMap.computeIfAbsent(studySemester, k -> new ArrayList<>()).add(courseDTO);
        }
        // 输出分类结果
        for (Map.Entry<String, List<CourseDTO>> entry : classifiedMap.entrySet()) {
            String studySemester = entry.getKey();
            List<CourseDTO> courseDTOList = entry.getValue();
            userGetAllClassDTOS.add(new UserGetAllClassDTO(studySemester, courseDTOList));
        }
        return userGetAllClassDTOS;
    }
    @Override
    public List<CourseDTO> getTopClassById(Integer id) {
        User user = userMapper.selectById(id);
        List<UserCourse> data = userCourseMapper.selectTopClass(id,user.getType());
        System.out.println(data);
        List<CourseDTO> courseList = new ArrayList<>();
        for (UserCourse datum : data) {
//            System.out.println(datum.getCourseId()+"----------------");
            CourseDTO courseDTO = courseMapper.selectByCourseId(datum.getCourseId());
            courseDTO.setIsTop(datum.getIsTop());
            courseDTO.setName(userMapper.selectById(datum.getUserId()).getName());
            courseDTO.setIsPigeonhole(datum.getIsPigeonhole());
            courseDTO.setType(datum.getType());
            courseList.add(courseDTO);
        }

        return courseList;
    }

    @Override
    public List<UserGetAllClassDTO> getAllClass(Integer id) {
        List<UserCourse> data = userCourseMapper.selectAllClass(id);
        List<CourseDTO> courseList = new ArrayList<>();
        List<UserGetAllClassDTO> userGetAllClassDTOS = new ArrayList<>();
        for (UserCourse datum : data) {
            CourseDTO courseDTO = courseMapper.selectByCourseId(datum.getCourseId());
            courseDTO.setName(userMapper.selectById(datum.getUserId()).getName());
            courseDTO.setIsTop(datum.getIsTop());
            courseDTO.setIsPigeonhole(datum.getIsPigeonhole());
            courseList.add(courseDTO);
        }
        Map<String, List<CourseDTO>> classifiedMap = new HashMap<>();
        for (CourseDTO courseDTO : courseList) {
            String studySemester = courseDTO.getAcademicYear() +" "+courseDTO.getSemester();
            // 如果该 id 还没有对应的列表，则创建一个新列表
            classifiedMap.computeIfAbsent(studySemester, k -> new ArrayList<>()).add(courseDTO);
        }
        // 输出分类结果
        for (Map.Entry<String, List<CourseDTO>> entry : classifiedMap.entrySet()) {
            String studySemester = entry.getKey();
            List<CourseDTO> courseDTOList = entry.getValue();
            userGetAllClassDTOS.add(new UserGetAllClassDTO(studySemester, courseDTOList));
        }

        return userGetAllClassDTOS;
    }

    @Override
    public UserGetDivideClass searchNormalClass(UserCourseParam userCourseParam) {
        List<UserCourse> data1 = userCourseMapper.selectTeachClass(userCourseParam.getUserId());
        List<UserCourse> data2 = userCourseMapper.selectLearnClass(userCourseParam.getUserId());
        List<UserCourse> data3 = userCourseMapper.selectAssistClass(userCourseParam.getUserId());
        return new UserGetDivideClass(getDivideClass(userCourseParam,data1),getDivideClass(userCourseParam,data2),getDivideClass(userCourseParam,data3));
    }
    @Override
    public UserGetDivideClass searchPigeonholeClass(UserCourseParam userCourseParam) {
        List<UserCourse> data2 = userCourseMapper.selectPigeonholeStudyClass(userCourseParam.getUserId());
        List<UserCourse> data1 = userCourseMapper.selectPigeonholeTeachClass(userCourseParam.getUserId());
        List<UserCourse> data3 = userCourseMapper.selectPigeonholeAssistClass(userCourseParam.getUserId());
        return new UserGetDivideClass(getDivideClass(userCourseParam,data1),getDivideClass(userCourseParam,data2),getDivideClass(userCourseParam,data3));
    }
    @Override
    public UserGetDivideClass getPigeonholeClass(Integer id) {
        List<UserCourse> data2 = userCourseMapper.selectPigeonholeStudyClass(id);
        List<UserCourse> data1 = userCourseMapper.selectPigeonholeTeachClass(id);
        List<UserCourse> data3 = userCourseMapper.selectPigeonholeAssistClass(id);
        return new UserGetDivideClass(getDealClass(data1),getDealClass(data2),getDealClass(data3));
    }
    @Override
    public Boolean createClass(CourseDTO course) {
        course.setCourseCode(CourseCodeGenerator.generateCourseCode());
        course.setStudent_number(1);
        System.out.println(course);
        getStuNum();
        return courseMapper.createCourse(course);
//        return true;
    }

    @Override
    public Boolean editClass(CourseDTO course) {

        course.setStudent_number(1);
        System.out.println(course);
        return courseMapper.updateCourse(course);

    }

    @Override
    public boolean unPigeonholeClass(UserCourseParam courseParam) {
        return userCourseMapper.unPigeonholeClass(courseParam);
    }

    @Override
    public List<User> getStudent(UserCourseParam courseParam) {
        PageHelper.startPage(courseParam.getPage()-1, courseParam.getPageSize()); // 页码从1开始
        List<UserCourse> data =  userCourseMapper.getStudent(courseParam);
        PageInfo<UserCourse> pageInfo = new PageInfo<>(data);
        List<User> users = new ArrayList<>();
        for (UserCourse userCourse : pageInfo.getList()) {
            User user = userMapper.selectById(userCourse.getUserId());
            users.add(user);
        }
        return users;
    }


    @Override
    public List<UserGetAllClassDTO> getLearnClass(Integer id) {
        List<UserCourse> data = userCourseMapper.selectLearnClass(id);
        return getDealClass(data);
    }

    @Override
    public List<UserGetAllClassDTO> getTeachClass(Integer id) {
        List<UserCourse> data = userCourseMapper.selectTeachClass(id);
        return getDealClass(data);
    }

    @Override
    public List<UserGetAllClassDTO> getAssistClass(Integer id) {
        List<UserCourse> data = userCourseMapper.selectAssistClass(id);
        return getDealClass(data);
    }

    @Override
    public User getUserInfo(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean pigeonholeClass(UserCourseParam courseParam) {
        return userCourseMapper.pigeonholeClass(courseParam);
    }


    public UserCourseDTO getUserCourse(UserCourseParam param) {
        return userCourseMapper.getUser(param);
    }

    @Override
    public boolean unTopById(UserCourseParam courseParam) {
        return userCourseMapper.unTopById(courseParam);
    }

    @Override
    public boolean topById(UserCourseParam courseParam) {
        return userCourseMapper.topById(courseParam);
    }

    @Override
    public JsonResult<?> addClass(UserAddCourseParam userAddCourseParam) {
        Course course = courseMapper.selectByCourseCode(userAddCourseParam);
        if (course == null) {
            return JsonResult.error("课程不存在");
        }
        UserCourseParam userCourseParam = new UserCourseParam(course.getId(), userAddCourseParam.getType(), userAddCourseParam.getUserId());
        if (userCourseMapper.isAlreadyAdd(userCourseParam) != null) {
            return JsonResult.error("课程已添加");
        }
        userCourseMapper.addClass(userCourseParam);
        getStuNum();
        return JsonResult.success("添加成功");
    }


    @Override
    public boolean deleteById(UserCourseParam userCourseParam) {
        getStuNum();
        return userCourseMapper.deleteById(userCourseParam);
    }
    @Override
    public boolean deleteTeachById(UserCourseParam userCourseParam) {
        return userCourseMapper.deleteTeachById(userCourseParam);
    }
    @Override
    public boolean update(UserCourse userCourse) {

        return userCourseDao.updateById(userCourse) > 0;
    }

    @Override
    public boolean placeToFile(Integer cid) {
        return false;
    }

    @Override
    public List<UserCourse> queryByCid(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id", id);
        return userCourseDao.selectByMap(map);
    }

    @Override
    public Map<String, Object> getTeacher(UserCourseParam param) {
        param.setPage((param.getPage() - 1) * param.getPageSize());
        List<TeacherDTO> list = userCourseDao.getTeacher(param);
        Integer count = userCourseDao.countTeacher(param);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("list", list);
        map1.put("num", count);
        return map1;
    }

    @Override
    public UserCourseDTO getUser(UserCourseParam param) {

        return userCourseMapper.getUser(param);
    }



    @Override
    public Map<String, Object> getUserByCid(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id",id);
        List<UserCourse> list = userCourseDao.selectByMap(map);//通过课程ID查询用户课程
        List<User> users = new ArrayList<>();
        for (UserCourse userCourse : list) {
            Integer userId = userCourse.getUserId();//通过用户课程获取用户id
            User user = userService.selectById(userId);
            users.add(user);
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("list", users);
        map1.put("num", users.size());
        return map1;
    }

    @Override
    public Map<String, Object> getUserByCidAndType(Integer cid, Integer type) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id", cid);
        map.put("type", type);
        List<UserCourse> list = userCourseDao.selectByMap(map);//通过课程ID查询用户课程
        List<User> users = new ArrayList<>();
        for (UserCourse userCourse : list) {
            Integer userId = userCourse.getUserId();//通过用户课程获取用户id
            User user = userService.selectById(userId);
            users.add(user);
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("list", users);
        map1.put("num", users.size());
        return map1;
    }

    /**
     * 列表查询
     */
//    @Override
//    public Map<String, Object> selectList(UserCourseParam param) {
//
//        List<UserCourse> list = userCourseMapper.selectList();//根据条件查询列表
//        List<UserCourseDTO> userCourseDTO = new ArrayList<>();
//        Map<String, Object> map = new HashMap<>();
//        map.put("total", list.size());
//        map.put("list", userCourseDTO);
//        return map;
//    }
    @Override
    public Map<String, Object> selectList(UserCourseParam param) {
        QueryWrapper<UserCourse> wrapper = condition(param);
        List<UserCourse> list = userCourseDao.selectList(wrapper);//根据条件查询列表
        List<UserCourseDTO> userCourseDTO = new ArrayList<>();
        for (UserCourse userCourse : list) {
            UserCourseDTO dto = new UserCourseDTO();
            BeanUtils.copyProperties(userCourse, dto);
            CourseDTO courseDTO = courseService.queryById(userCourse.getCourseId());
            User user = userService.selectById(courseDTO.getUserId());
            dto.setCourseList(courseDTO);
            dto.setUser(user);
            userCourseDTO.add(dto);
        }
        Map<String, Object> map = new HashMap<>();

        map.put("total", list.size());
        map.put("list", userCourseDTO);
        System.out.println("查询结果: " + list);
        return map;
    }
    /**
     * 列表查询条件
     */
    public QueryWrapper<UserCourse> condition(UserCourseParam param) {
        QueryWrapper<UserCourse> wrapper = new QueryWrapper<>();

        if (param.getUserId() != null) {
            wrapper.eq("user_id", param.getUserId());
        }
        if (param.getType() != null) {
            wrapper.eq("type", param.getType());
        }
        if (param.getCourseId() != null) {
            wrapper.eq("course_id", param.getCourseId());
        }
        return wrapper;
    }

    @Override
    public Integer getStuNumByCid(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("course_id", id);
        map.put("type", 0);//学生用户
        List<UserCourse> list = userCourseDao.selectByMap(map);
        return list.size();
    }
//
//    /**
//     * 列表查询条件
//     */
//    public QueryWrapper<UserCourse> condition(UserCourseParam param) {
//        QueryWrapper<UserCourse> wrapper = new QueryWrapper<>();
//
//        if (param.getUserId() != null) {
//            wrapper.eq("user_id", param.getUserId());
//        }
//        if (param.getType() != null) {
//            wrapper.eq("type", param.getType());
//        }
//        if (param.getCourseId() != null) {
//            wrapper.eq("course_id", param.getCourseId());
//        }
//        return wrapper;
//    }
//
    /**
     * 新增数据
     */
    @Override
    public boolean insert(UserCourse userCourse) {
        boolean b = userCourseDao.insert(userCourse) > 0;
        if(userCourse.getType()==0){//新增学生作业
            insertStuWork(userCourse);
        }
        return b;
    }
    /**
     * 新增助教
     */
    @Override
    public boolean insertAssist(UserCourse userCourse) {
        List<UserCourse> userCourse1 = userCourseMapper.selectById(userCourse);
        if (userCourse1.isEmpty())
        {
            return  userCourseMapper.insertAssist(userCourse);
        }else {
            return  false;
        }

    }
    //课程的所有学生作业新增
    public void insertStuWork(UserCourse userCourse) {
        List<Work> works = userCourseDao.getWork(userCourse.getCourseId());
        List<StuWork> stuWorks=new ArrayList<>();
        for (Work work : works) {
            if (work.getStatus()==2){//已发布
                StuWork stuWork=new StuWork();
                stuWork.setWorkId(work.getId());
                stuWork.setUserId(userCourse.getUserId());
                User user=userService.selectById(userCourse.getUserId());
                stuWork.setUsername(user.getName());
                stuWork.setContent(work.getContent());//发布作业内容
                stuWorks.add(stuWork);
            }
        }
        stuWorkService.saveBatch(stuWorks);
    }


//    /**
//     * 修改数据
//     */
//    @Override
//    public boolean update(UserCourse userCourse) {
//
//        return userCourseDao.updateById(userCourse) > 0;
//    }
//
//    /**
//     * 归档全部用户课程
//     */
//    @Override
//    public boolean placeToFile(Integer cid) {
//        List<UserCourse> list = userCourseDao.getByCid(cid);
//        for (UserCourse userCourse : list) {
//            userCourse.setIsPigeonhole(0);
//        }
//        return updateBatchById(list);
//    }
//
//    /**
//     * 通过主键删除数据
//     */
//    @Override
//    public boolean deleteById(Integer id) {
//        return userCourseDao.deleteById(id) > 0;
//    }
}
